package cn.huolabao.controller;

import cn.huolabao.common.core.exception.LCException;
import cn.huolabao.common.core.utils.R;
import cn.huolabao.dto.UserDetailDto;
import cn.huolabao.model.SysUser;
import cn.huolabao.service.SysUserService;
import cn.huolabao.vo.portal.AuthVo;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.HttpHeaders;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequiredArgsConstructor
@RequestMapping("/auth")
@Api(tags = "登陆登出")
public class AuthController {

    private final SysUserService userService;
    private final RedisTemplate<String, Object> redisTemplate;
    private final DefaultKaptcha producer;

    @PostMapping("/login")
    @ApiOperation(value = "用户登陆", httpMethod = "POST")
    public R login(@ApiParam(name = "用户Vo", value = "传入json格式", required = true) @RequestBody AuthVo authVo) {
        String code = (String) redisTemplate.opsForValue().get(authVo.getCtoken());
        if (ObjectUtils.isEmpty(code) || !code.equalsIgnoreCase(authVo.getCode())) {
            throw new LCException("验证码错误");
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(authVo, sysUser);
        String username = authVo.getUsername();
        String password = authVo.getPassword();
        SysUser user = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (ObjectUtils.isEmpty(user)) {
            throw new LCException("用户不存在");
        }
        return userService.login(username, password);
    }


    @RequestMapping("/kaptcha")
    @ApiOperation(value = "获取验证码", httpMethod = "GET")
    public R kaptcha() throws IOException {
        String text = producer.createText();
        BufferedImage image = producer.createImage(text);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", outputStream);
        Map<String, String> map = new HashMap<>();
        String ctoken = UUID.randomUUID().toString().replace("-", "");
        map.put("ctoken", ctoken);
        Base64.Encoder encoder = Base64.getEncoder();
        map.put("image", encoder.encodeToString(outputStream.toByteArray()));
        ValueOperations<String, Object> ops = redisTemplate.opsForValue();
        ops.set(ctoken, text, 300, TimeUnit.SECONDS);
        return R.ok().data(map);
    }

    @GetMapping("/info/{username}")
    public UserDetailDto info(@PathVariable("username") String username) {
        SysUser sysUser = userService.getOne(Wrappers.<SysUser>query().lambda().eq(SysUser::getUsername, username));
        if (ObjectUtils.isEmpty(sysUser)) {
            throw new RuntimeException("用户名不存在:" + username);
        }
        return userService.getUserInfo(sysUser);
    }

    @RequestMapping("/logout")
    @ApiOperation(value = "退出登陆", httpMethod = "POST")
    public R logout(HttpServletRequest request) {
        String token = request.getHeader(HttpHeaders.AUTHORIZATION);
        redisTemplate.delete(token.replace("Bearer ", ""));
        return R.ok("退出成功");
    }
}
